<?php

namespace App\Modules\Admin\Services\Bus;

use App\Exceptions\ApicrzsExceptions;
use App\Library\Junda\src\CardService;
use App\Modules\Admin\Entities\Member\UserCardModel;
use App\Modules\Admin\Entities\Water\WaterOrderModel;
use App\Modules\Admin\Services\BaseService;
use EasyWeChat\Pay\Application as payApp;
use Illuminate\Support\Facades\DB;

//充值记录
class ChargeService extends BaseService
{


    public function __construct(WaterOrderModel $model)
    {
        $this->model = $model;
        $this->with=['user_info'];
    }
    public function lists(array $params) : array
    {
        $params['where_callback'] = function($query) use ($params){
            $request = request();
            // 按照名称进行搜索
            $query->where('type', 'recharge') ;
            $query->where('status', 1) ;
            $order_sn = $request->input('order_sn', '');
            if (!empty($order_sn)){
                $query->where('order_sn', $order_sn);
            }
            $card_no = $request->input('card_no', '');
            if (!empty($card_no)){
                $query->where('card_no', $card_no);
            }

            $pay_type = $request->input('pay_type', '');
            if (!empty($pay_type)){
                $query->where('pay_type', $pay_type);
            }
            $status_end_day = $request->input('status_end_day', []);
            if (!empty($status_end_day)){
                [$status_time,$end_time] =  $status_end_day;
                $query->whereBetWeen('created_time', [$status_time, $end_time]);
            }
        };
        return parent::lists($params); // TODO: Change the autogenerated stub
    }
    // 后台 充值
    public function createRecharge($params)
    {
        $card_no = $params['card_no'];
        $card_info = UserCardModel::getInstance()->getUserByCardNo($card_no);
        $remaining_value = $card_info['remaining_value'];
        $buy_money = $params['buy_money'];
        $valueBefore = $balance = $card_info['remaining_value'];
        $valueAfter = $remaining_value = $card_info['remaining_value'] + $params['total_price'];

        $coupon_id = $params['coupon_id']??0;
        $con_money = $params['con_money'];
        $give_money= $buy_money - $con_money;
        $order_insert = [
            'user_card_id' => $card_info['user_card_id'] ?? 0,
            'user_id' => $card_info['user_id'],
            'card_no' => $card_no,
            'coupon_id' => $coupon_id,
            'order_sn' => '',
            'type' => $params['type'],
            'value_before' => $valueBefore,
            'value_after' => $valueAfter,
            'amount' => $con_money,
            'buy_money' => $buy_money,
            'total_price' => $buy_money,
            'give_price' =>$give_money,
            'payment_method' => $params['payment_method'] ?? '',
            'usage_type' => $params['usage_type'] ?? '',
            'paid' => $this->user_id ?? 0,
            'operator_name' => $this->user_id ?? "",
            'pay_time'=>time(),
            'status'=>1,
            'remark' => $params['remark'] ?? ''
        ];

        exit(json_encode($order_insert));
        $transaction = parent::create($order_insert);
        $res_jd = CardService::ICAccountCharge($card_no,$con_money,$buy_money);
        if ($res_jd!=1){
            DB::rollBack();
            throw new ApicrzsExceptions('提交错误');
        }
        return [];
    }

    /**
     *  退款
     * @param $params
     * @return array|mixed[]
     */
    public function refundRecharge($params)
    {

//        $param = [
//            'order_sn'=>'',
//            'refund_amount'=>'1',
//            'out_refund_no'=>rand_str(6),
//        ];
//        $this->refundRecharge($param);

        $out_trade_no=$params['order_sn'];
        $total=$params['refund_amount'];
        $out_refund_no=$params['out_refund_no'];
        $refunds_params=[
            'out_trade_no'=>$out_trade_no,
            'out_refund_no'=>$out_refund_no,
            "amount"=>[
                "refund"=> $total*100,
                'total'=>$total*100,                                                  // 订单总金额，单位为分，只能为整数
                "currency" => "CNY"
            ]
        ];
        $wechat_config = getWxConfig('MiniApp');
        // 创建微信支付对象
        $wechat = new payApp($wechat_config);
        $refunds_response = $wechat->getClient()->postJson("/v3/refund/domestic/refunds",$refunds_params);
        $refunds_result = $refunds_response->toArray(false);

        exit(json_encode($params));
        return   $refunds_result;
    }
}
